package com.example.demojimmer.domain.userauth.task;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class Task {
    @Autowired
    ApplicationContext applicationContext;

    //获取全部uir
    public void synTask3() {

        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();


        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : map.keySet()) {
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternValues();

            for (String url : patterns) {
                urlList.add(url);
            }
        }

        System.out.println("uri>>>>>>>>>>>");
        System.out.println(urlList);

    }


    //扫描PreAuthorize注解的
    public void scanMethodsWithAnnotation() throws ClassNotFoundException {
        List<String> permissions = new ArrayList<>();
        //扫描类使用hutool
        Set<Class<?>> classes1 = ClassUtil.scanPackage("com.example");
        for (Class candidate : classes1) {

            for (Method method : candidate.getDeclaredMethods()) {
                // 检查方法是否包含自定义注解
                if (method.isAnnotationPresent(PreAuthorize.class)) {
                    System.out.println("Found method with custom annotation: " + method.getName());
                    // 这里可以添加更多的逻辑，例如调用方法或记录方法信息
                    PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
                    String value = annotation.value();
                    String permission = StrUtil.subBetween(value, "'");

                    permissions.add(permission);
                }
            }

        }


        System.out.println("扫描到的注释");
        System.out.println(permissions);
    }
}
